const jwt = require('jsonwebtoken');

const data={
    "super":["resources","chapters","courses","","steps","teachers","students","classes","users"],
    "admin":["resources","chapters","courses","tasks","steps"],
    "teacher":["resources","chapters","tasks","steps"],
}
module.exports = async(ctx,next) => {
    //如果是登录 则所有人都可操作
    if(ctx.request.url.indexOf("/login")>0){
        await next();
        return;
    }
    //获取token里的用户信息
    let user= jwt.decode(ctx.request.header.authorization.split(" ")[1])
    if(!user){
        ctx.throw(200, {
            errCode: 1,
            msg: 'token错误'
        })
    }
    const type=user.type  
    //如果不是学生 
    if(type!=="student"){
        const url = ctx.request.url.split("?")[0].split("/")[1];
      
        //校验是否有权限  
        let right=data[type]?data[type].indexOf(url):-1
        if(right==-1){
            ctx.throw(200, {
                errCode: 1,
                msg: '没有权限访问'
            })
        } else{
            await next();
            return;
        } 
    }else{
        const reg1=/students\/.*?\/tasks/
        const test1=reg1.test(ctx.request.url)
       
        const reg2=/tasks\/.*?\/records/
        const test2=reg2.test(ctx.request.url)

        if(test1||test2){
            await next();
            return;
          
        } else{
            ctx.throw(200, {
                errCode: 1,
                msg: '没有权限访问'
            })
        } 
    }
   
}
